<template>
  <div class="auto" >
    <validator name='v'>
      <form class="form-horizontal">
        <p class="bg-info text-center">机表收费</p>
        <div class="row" style="padding-top: 0.5em;">
          <div class="col-sm-3 form-input-group">
            <label for="f_paytype" class=" col-sm-2 control-label">付款方式:</label>
            <div class="col-sm-2">
              <v-select id="f_payment"
                        v-model="f_payment"
                        placeholder='请选择'
                        :value.sync="data.f_payment"
                        :options='paytype'
                        close-on-select clear-button>
              </v-select>
            </div>
          </div>
          <div class="col-sm-3 form-input-group">
            <label for="f_pregas" class=" control-label">用气量:</label>
            <input class="form-control" type="number"
                   v-model="data.f_pregas" placeholder="用气量"
                   v-scale = "[data.f_pregas, 2]" disabled>
          </div>
          <div class="col-sm-3 form-input-group">
            <label for="f_preamount" class="control-label">用气金额:</label>
            <input class="form-control"  type="number" v-model="data.f_preamount"
                   v-scale = "[data.f_preamount, 2]"
                   placeholder="用气金额" disabled>
          </div>
          <div class="col-sm-3 form-input-group">
            <label for="f_print" class="control-label">打印格式:</label>
            <div class="col-sm-2">
              <v-select id="print"
                        v-model="data.f_print"
                        placeholder='请选择'
                        :value.sync="data.f_print"
                        :options='printstyle'
                        close-on-select clear-button>
              </v-select>
            </div>
          </div>
        </div>
        <div class="row" style="padding-top: 0.5em;">
          <div class="col-sm-3 form-input-group">
            <label for="f_balance"  class="control-label">上期结余:</label>
            <input class="form-control"  type="number" v-model="data.f_balance"
                   v-scale="[data.f_balance,2]" placeholder="应收金额" disabled>
          </div>

          <div class="col-sm-3 form-input-group">
            <label for="f_overdue" class="control-label">滞纳金:</label>
            <!-- <span class="col-sm-2 form-control-static">{{model.f_totalcost}}</span> -->
            <input class="form-control"  type="number" v-model="newOverdue"
                   v-scale="[newOverdue,2]" placeholder="滞纳金" @blur="calOverdue()" readonly>
            <button type="button" name="button" class="btn btn-link" @click="show=true">修改</button>
          </div>

          <div class="col-sm-3 form-input-group">
            <label for="f_lowest" class="control-label">最低缴费:</label>
            <!-- <span class="col-sm-2 form-control-static">{{model.f_totalcost}}</span> -->
            <input class="form-control"  type="number" v-model="data.f_lowest"
                   v-scale = "[data.f_lowest, 2]" placeholder="应收金额" disabled>
          </div>

          <div class="col-sm-3 form-input-group">
            <label for="f_curbalance" class="control-label">本期结余:</label>
            <input class="form-control"  type="number" v-model="curbalance"  placeholder="0"
                   v-scale = "[curbalance, 2]" disabled>
          </div>


        </div>
        <div class="row" style="padding-top: 0.5em;">

          <div class="col-sm-6 form-input-group">
            <label for="f_curbalance" class="col-sm-2 control-label">备注:</label>
            <input class="form-control"  type="text" v-model="row.f_comments"  placeholder="<无备注>" disabled>
          </div>
          <div class="col-sm-3 form-input-group">
            <label for="f_totalcost" class=" col-sm-2 control-label">应收金额:</label>
            <input class="form-control"  type="number" v-model="data.f_totalcost"
                   v-scale = "[data.f_totalcost, 2]" placeholder="应收金额" disabled>
          </div>
          <div class="col-sm-3 form-input-group">
            <label for="f_collection" class="control-label">收款:</label>
            <input id="f_collection" class="form-control" type="number" v-model="data.f_collection"
                   v-validate:f_collection='{dctest: [ Math.trunc(data.f_lowest), ">=" ] }'  v-scale = "[data.f_collection, 2]"
                   @keyup.enter="confirm()">
          </div>
          <span class="col-sm-12" v-if="$v.f_collection.dctest" style="color:red;text-align:right">收款不能小于最低金额</span>
        </div>
      </form>
      <print-bill :show="print" :data='data' :bill-url='billUrl' @toggle="close" v-ref:printbill></print-bill>
      <div class="text-right" style="margin-top: 1%">
        <button class="btn btn-success" @click="confirm()"  :disabled='!$v.valid'>确认</button>
        <button class="btn btn-default" @click="clean()">取消</button>
      </div>
    </validator>
    <idverify :show.sync="show" @change-con="changeOverdue"></idverify>
  </div>
</template>
<script>
  import AppData from '../../../stores/AppData'

  /**
   *售气收费
   *机表收费组件
   */
  export default {
    title: '机表收费',
    data () {
      return {
        newOverdue: 0,
        print: false,
        isConfirm: true,
        show: false,
        billUrl: ''
        // 欠费数
        // oweNum: 0
      }
    },
    props: ['data', 'owenum', 'row'],
    ready () {
      this.newOverdue = this.data.f_overdue
      console.log('s数据。，。。。。', this.data)
    },
    methods: {
      confirm () {
        console.log('data', this.data)
        console.log('owenum', this.owenum)
        console.log('row', this.row)
        if (this.data.f_collection >= Math.trunc(this.data.f_lowest)) {
          if (!this.isConfirm) {
            return
          }
          this.isConfirm = false
          this.data.f_curbalance = this.curbalance
          this.data.f_payment = this.data.f_payment ? this.data.f_payment[0] : '现金缴费'
          this.data.f_overdue = this.newOverdue
          // 未滞纳金修改添加，将修改的值，原因添加到this.data.logicmodel中
          // 如果有变更原因说明有变更
          if (this.f_cause && this.f_cause.length > 0) {
            this.data.f_paydelaypay = this.f_paydelaypay // 应缴滞纳金
            this.data.f_delaypay = this.f_delaypay // 实缴滞纳金
            this.data.f_cause = this.f_cause // 变更原因
          }
          // 设置自动下账的欠费明细
          this.autoaccount()
          this.$MachineChargeService.marchineCharge(this.data, this.row)
            .then((res) => {
              this.data.id = res.data
              this.data.f_bill_type = '机表收费'
              this.data.f_bill_style = this.data.f_print[0]
              // 主分支不做发票处理
              // this.$showAlert('机表缴费成功', 'success', 2000)
              // this.$dispatch('success', '机表收费', this.data, res)
              console.log('开始打票')
              if (this.data.f_pregas > 0) {
                this.billUrl = 'rs/report/machine_bill'
              } else {
                this.billUrl = 'rs/report/pre_sell'
              }
              this.print = true
            }).catch((error) => {
              if (error.status === 603) {
                this.$error('重复提交')
                return
              }
              this.$dispatch('error', '机表收费', this.data, error)
            }
          )
        }
      },
      autoaccount () {
        let arr = []
        let account = 0
        // 将所有的欠费记录，在收费时判断是交完费，影响到发票打印
        // this.oweNum = this.calowe.length
        // 判断是否有滞纳金,第一笔没有滞纳金，说明所有欠费都没有滞纳金
        // if (this.data.rows.length === 0 || (this.data.rows.length > 0 && this.data.rows[0].overdue <= 0)) {
        //   account = (this.data.f_collection - 0) + (this.data.f_balance - 0)
        // } else {
        //   account = (this.data.f_collection - 0) - (this.data.f_lowest - 0)
        // }
        // this.data.rows.forEach((item) => {
        //   if (item.overdue <= 0) {
        //     if (account.toFixed(2) >= item.f_oughtfee) {
        //       // 可自动下账
        //       arr.push(item)
        //       account = account - item.f_oughtfee
        //     } else {
        //       // 存到账户结余
        //       return
        //     }
        //   } else {
        //     arr.push(item)
        //   }
        // })

        if (this.data.start_index === -1) {
          account = (this.data.f_collection - 0) + this.data.f_balance
          let temp = account.toFixed(0)
          this.data.rows.forEach((item) => {
            if (temp >= Math.trunc(item.f_oughtfee)) {
              // 可自动下账
              arr.push(item)
              account = account - item.f_oughtfee
              temp = account.toFixed(0)
            } else {
              // 存到账户结余
              return
            }
          })
        } else {
          account = (this.data.f_collection - 0) - this.data.f_lowest
          let temp = account.toFixed(0)
          this.data.rows.forEach((item, index) => {
            if (index > (this.data.end_index > 0 ? this.data.end_index : 0)) {
              if (temp >= Math.trunc(item.f_oughtfee)) {
                // 可自动下账
                arr.push(item)
                account = account - item.f_oughtfee
                temp = account.toFixed(0)
              } else {
                // 存到账户结余
                return
              }
            } else {
              arr.push(item)
            }
          })
        }

        this.data.rows = arr
      },
      calOverdue () {
        console.log('原来滞纳金..', this.data.f_overdue)
        console.log('新滞纳金..', this.newOverdue)
        this.data.f_lowest = this.data.f_lowest - (this.data.f_overdue - this.newOverdue)
        this.data.f_totalcost = this.data.f_totalcost - (this.data.f_overdue - this.newOverdue)
        this.data.f_overdue = this.newOverdue
      },
      clean () {
        this.$dispatch('success', '机表收费', this.data)
        this.$info('取消操作')
      },
      close () {
        this.print = false
        this.clean()
      },
      changeOverdue (val, reason) {
        this.$set('f_paydelaypay', this.newOverdue) // 应交滞纳金
        this.newOverdue = val // 实缴滞纳金
        this.$set('f_delaypay', this.newOverdue) // 实缴滞纳金
        this.$set('f_cause', this.reason) // 实缴滞纳金
        this.calOverdue()
      }
    },
    watch: {
      'data.f_overdue' (val) {
        this.newOverdue = val
      },
      'splitAll' (val) {
        console.log('分表用气量观察，，', val)
        this.data.f_pregas = this.data.f_pregas - val
      }
    },
    computed: {
      'curbalance' () {
        console.log('计算属性////', this.data)
        // if ((this.data.f_collection - 0) < this.data.f_lowest) {
        //   return this.data.f_balance
        // }
        let account = 0
        // let account = (this.data.f_collection - 0) - this.data.f_totalcost
        // 判断是否有滞纳金,第一笔没有滞纳金，说明所有欠费都没有滞纳金

        if (this.data.start_index === -1) {
          account = (this.data.f_collection - 0) + this.data.f_balance
          let temp = account.toFixed(0)
          this.data.rows.forEach((item) => {
            if ((temp - 0) >= Math.trunc(item.f_oughtfee)) {
              // 可自动下账
              account = account - item.f_oughtfee
              temp = account.toFixed(0)
            } else {
              // 存到账户结余
              return
            }
          })
        } else {
          account = (this.data.f_collection - 0) - this.data.f_lowest
          let temp = account.toFixed(0)
          this.data.rows.forEach((item, index) => {
            if (index > (this.data.end_index > 0 ? this.data.end_index : 0)) {
              if ((temp - 0) >= Math.trunc(item.f_oughtfee)) {
                // 可自动下账
                account = account - item.f_oughtfee
                temp = account.toFixed(0)
              } else {
                // 存到账户结余
                return
              }
            }
          })
        }
        // // }

        console.log('账户结余', account)
        return account.toFixed(2)
      },
      paytype () {
        return AppData.getParam('付款方式')
      },
      printstyle() {
        return AppData.getParam('打印格式')
      }
    }
  }
</script>
